package cn.cnf.service.impl;

import cn.cnf.common.enums.WorkType;
import cn.cnf.common.exception.CustomException;
import cn.cnf.common.utils.UserRequestUtil;
import cn.cnf.entity.Comic;
import cn.cnf.entity.Comment;
import cn.cnf.entity.Novel;
import cn.cnf.entity.User;
import cn.cnf.entity.vo.ChildrenComment;
import cn.cnf.entity.vo.CommentArea;
import cn.cnf.entity.vo.CommentInfo;
import cn.cnf.entity.vo.ParentComment;
import cn.cnf.mapper.CommentMapper;
import cn.cnf.service.ComicService;
import cn.cnf.service.CommentService;
import cn.cnf.service.NovelService;
import cn.cnf.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;

/**
 * 服务接口实现
 *
 * @author ZhuMeiYi
 * @description
 * @since 2020-12-04 15:18:43
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Service
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private final CommentMapper commentMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private ComicService comicService;
    @Autowired
    private NovelService novelService;

    @Override
    public String delete(String id) {
        Comment comment = getById(id);
        if (comment==null){
            throw new CustomException("评论不存在");
        }
        User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());

        // 如果不是用户本人
        if (!user.getId().equals(comment.getAuthorId())){
            // 判断是否为管路员
            if (!UserRequestUtil.getCurrentUserRole().contains("ADMIN")) {
                // 非管理员则抛异常
                throw new CustomException("非用户本人不能删除评论");
            }
        }
        // 删除本条及本条下面的评论
        if (!remove(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getId, id)
                .or()
                .eq(Comment::getParentId, id))){
            throw new CustomException("删除失败");

        }
        Comic comic = comicService.getById(comment.getFromId());
        Novel novel = novelService.getById(comment.getFromId());
        if (comic!=null){
            comicService.updateCommentNum(comic.getId(),comic.getCommentNum()-1);
        }else if (novel!=null){
            novelService.updateCommentNum(novel.getId(),novel.getCommentNum()-1);
        }else {
            throw new CustomException("不存在的作品类型");
        }
        return id;

    }

    @Override
    public String addComment(CommentInfo comment) {
        // 如果是楼中回复
        if (!StringUtils.isBlank(comment.getParentId())) {
            // 判断本层评论存在
            Comment parent = getById(comment.getParentId());
            if (parent == null) {
                throw new CustomException("本层评论已失效");
            }
            // 本层存在则填入
            comment.setParentId(parent.getId());
            // 如果没有回复id
            if (StringUtils.isBlank(comment.getReplyId())){
                throw new CustomException("没有填入回复评论的id");
            }
            Comment reply = getById(comment.getReplyId());
            if (reply==null){
                throw new CustomException("您要回复的评论已失效");
            }
            comment.setReplyAuthorId(reply.getAuthorId());
        }else {
            // 设置非楼中回复标识
            comment.setParentId("0");
        }
        User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());
        comment.setAuthorId(user.getId());
        WorkType type = WorkType.getByValue(comment.getWorkType());
        if (WorkType.COMIC.equals(type)){
            // 如果是漫画给漫画加评论数
            String comicId = comment.getFromId();
            Comic comic = comicService.getById(comicId);
            comicService.updateCommentNum(comicId,comic.getCommentNum()+1);
        }else if (WorkType.NOVEL.equals(type)){
            String novelId = comment.getFromId();
            Novel novel = novelService.getById(novelId);
            novelService.updateCommentNum(novelId,novel.getCommentNum()+1);
        }else {
            throw new CustomException("未知作品类型");
        }

        Comment c = comment.toComment();
        // 增加评论
        save(c);
        return c.getId();
    }

    /**
     * 全部评论
     *
     * @param fromId
     * @return
     */
    @Override
    public List<CommentArea> getAllComments(String fromId) {
        // 获得父级评论
        List<ParentComment> list = commentMapper.getComments(fromId);

        LinkedList<CommentArea> commentAreas = new LinkedList<>();

        for (ParentComment comment : list) {
            // 评论下的子评论
            List<ChildrenComment> children = commentMapper.getChildrenComments(fromId,comment.getId());
            CommentArea commentArea = new CommentArea();
            commentArea.setId(comment.getId());
            commentArea.setAuthorId(comment.getAuthorId());
            commentArea.setCreateTime(comment.getCreateTime());
            commentArea.setNickname(comment.getNickname());
            commentArea.setContent(comment.getContent());
            commentArea.setReply(children);
            commentAreas.add(commentArea);
        }
        return commentAreas;
    }
}